﻿using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System;
using Adp;
using Newtonsoft.Json.Linq;
using Yqd.Enm;
using Adp.Common;
using Yqd.Models;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Yqd.Core
{
    public class DepartmentHostService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (DateTime.Now.Hour == 23)
                {
                    Logs.Information<DepartmentHostService>($"------开始更新部门-----");
                    var ddService = Fn.GetService<DdService>();
                    var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
                    var sc = ddService.scopesV2(config.TenantId);
                    var arr = new List<departmentInfo>();
                    foreach (var item in sc["deptVisibleScopes"])
                    {
                        LoadDepartment(item.ToString(), config.TenantId, arr);
                    }

                    //var result = JsonConvert.SerializeObject(arr);
                    using (var ctx = new YqdContext())
                    {
                        var departments = ctx.Yqd_Department.ToList();
                        if (arr.Any())
                        {
                            foreach (var item in arr)
                            {
                                //if (item.organizationName == "稠城大队")
                                //{
                                //    var xx = "";
                                //}
                                var dept = departments.Where(x => x.OrganizationCode == item.organizationCode).SingleOrDefault();
                                if (dept == null)
                                {
                                    //var info = ddService.GetOrganizationInfo(item, config.TenantId);

                                    var department = new Yqd_Department
                                    {
                                        OrganizationCode = item.organizationCode,
                                        ParentCode = item.parentCode,
                                        Name = item.organizationName,
                                        InstitutionLevelCode = item.institutionLevelCode,
                                        InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", item.institutionLevelCode),
                                        TypeCode = item.typeCode,
                                        TypeName = item.TypeName,
                                        isLeaf = item.Leaf,
                                        Status = item.status,
                                        UpdateTime = DateTime.Now
                                    };
                                    ctx.Yqd_Department.Add(department);
                                    var re = ctx.SaveChanges();
                                    departments.Add(department);
                                }
                                else
                                {
                                    dept.ParentCode = item.parentCode;
                                    dept.Status = item.status;
                                    dept.isLeaf = item.Leaf;
                                    dept.InstitutionLevelCode = item.institutionLevelCode;
                                    dept.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", item.institutionLevelCode);
                                    dept.TypeCode = item.typeCode;
                                    dept.TypeName = item.TypeName;
                                    dept.UpdateTime = DateTime.Now;
                                    ctx.SaveChanges();
                                }
                            }

                            Logs.Information<DepartmentHostService>($"------部门更新完成-----");
                        }
                    }
                }
                Thread.Sleep(60000);
                await Task.Delay((1000 * 60 * 60), stoppingToken);
            }
        }
        private void LoadDepartment(string organizationCode, int tenantId, List<departmentInfo> arr)
        {
            using (var ctx = new YqdContext())
            {
                var ddService = Fn.GetService<DdService>();
                var data = ddService.pageSubOrganizationCodes(organizationCode, tenantId);
                foreach (var item in data)
                {
                    var info = ddService.GetOrganizationInfo(item, tenantId);
                    //if (info["organizationName"].ToString() == "稠城大队")
                    //{
                    //    var xx = "";
                    //}
                    var depart = new departmentInfo
                    {
                        institutionLevelCode = info["institutionLevelCode"]?.ToString() ?? "",
                        organizationName = info["organizationName"]?.ToString(),
                        organizationCode = info["organizationCode"]?.ToString(),
                        typeCode = info["typeCode"]?.ToString() ?? "",
                        TypeName = info["typeName"]?.ToString() ?? "",
                        parentCode = info["parentCode"]?.ToString() ?? "",
                        Leaf = Convert.ToBoolean(info["leaf"]),
                        status = info["status"].ToString() == "F" ? 1 : 0,//1:禁用  0：启用
                    };
                    arr.Add(depart);

                    //if (UpdateDepartment(organizationCode, item, tenantId))
                    //{
                    //}
                    LoadDepartment(item.ToString(), tenantId, arr);

                }
            }
        }

        public class departmentInfo
        {
            public string institutionLevelCode { get; set; }

            public string organizationCode { get; set; }

            public string organizationName { get; set; }

            public string typeCode { get; set; }

            public string TypeName { get; set; }
            public string parentCode { get; set; }
            public bool Leaf { get; set; }

            public int status { get; set; }
        }
    }
}
